#include <iostream>
#include <time.h>
#include <unistd.h>
#include <sys/wait.h>
#include "BlockQueue.hpp"
#include "LockGuard.hpp"
#include "Task.hpp"

// 创建两个线程，一个生产者和一个消费者

class ThreadData
{
public:
    BlockQueue<Task> *bq;
    std::string name;
};
void *Producer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        // 往队列中生产数据
        // int data = rand() % 10 + 1; // [1, 10];
        // bq->Push(data);
        int x = rand() % 10; // [0, 9]
        usleep(rand() % 123);
        int y = rand() % 10;
        usleep(rand() % 123);
        char oper = opers[rand() % (opers.size())];
        Task t(x, y, oper);
        std::cout << "productor task: " << t.PrintTask() << std::endl;
        // std::cout << "Producer data: " << data << std::endl;
        bq->Push(t);
        // sleep(1);
    }
}
void *Consumer(void *args)
{
    // BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    //  BlockQueue<int> *bq = static_cast<BlockQueue<int> *>(args);
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        // // 在队列中消费数据
        // int data = 0;
        // bq->pop(&data);
        // std::cout << "Consumer data: " << data << std::endl;
        // sleep(1);
        Task t;
        td->bq->Pop(&t);
        t.Run();
        std::cout << "Consumer task: " << t.Printresult() << ", " << td->name << std::endl;
        // usleep(10000);
        sleep(1);
    }
}
int main()
{
    srand(time(nullptr) ^ getpid() ^ pthread_self());
    BlockQueue<Task> *bq = new BlockQueue<Task>();
    pthread_t c[3], p[2];
    ThreadData *t1 = new ThreadData();
    t1->bq = bq;
    t1->name = "thread-1";
    pthread_create(&c[0], nullptr, Consumer, t1);
    ThreadData *t2 = new ThreadData();
    t2->bq = bq;
    t2->name = "thread-2";
    pthread_create(&c[1], nullptr, Consumer, t2);
    ThreadData *t3 = new ThreadData();
    t3->bq = bq;
    t3->name = "thread-3";
    pthread_create(&c[2], nullptr, Consumer, t3);

    pthread_create(&p[0], nullptr, Producer, bq);
    pthread_create(&p[1], nullptr, Producer, bq);

    
    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(c[2], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);

    return 0;
}
